using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Diagnostics;

namespace MaskData
{
	public class MaskNode
	{
		private Dictionary<String, MaskElement> _Elements = new Dictionary<string,MaskElement>();
		private Dictionary<String, ElementType> _types;

		public Dictionary<String, MaskElement> Elements
		{
			get {
				return _Elements;
			}
		}
		public MaskNode(Dictionary<String, ElementType> types)
		{
			_types = types;
		}
		public MaskNode(List<ElementType> types)
		{
			_types = new Dictionary<string, ElementType>();
			foreach(ElementType type in types)
			{
				_types[type.FieldName] = type;
			}
		}

		public MaskElement GetFieldElement(String fieldName)
		{
			MaskElement maskElement = null;
			try
			{
				maskElement = _Elements[fieldName];
			}
			catch (KeyNotFoundException)
			{ }
			return maskElement;
		}

		public ElementType GetElementType(String fieldName)
		{
			ElementType eleType = null;
			try
			{
				eleType = _types[fieldName];
			}
			catch (KeyNotFoundException)
			{ }
			return eleType;
		}

		public void InitializeFromDataRow(DataRow row)
		{
			Debug.Assert(_Elements.Count == 0);
			_Elements.Clear();

			foreach(KeyValuePair<String, ElementType> typePair in _types)
			{
				Debug.Assert(typePair.Key == typePair.Value.FieldName);
				object value = row[typePair.Key];
				MaskElement element = typePair.Value.CreateMaskElement(value);
				_Elements[typePair.Key] = element;
			}

		}
		public void AddElement(MaskElement element)
		{
			_Elements[element.Type.FieldName] = element;
		}
		public void SaveToRow(DataRow row)
		{
			foreach (KeyValuePair<String, MaskElement> elementPair in _Elements)
			{
				elementPair.Value.SaveToRow(row);
			}
		}
	}
}
